package com.拷贝;
class Wife implements Cloneable{
     int age;
     String name;
    public Wife(String name,int age){
        this.name = name;
        this.age  = age;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Wife{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
class Husband implements Cloneable{
    String name;
    String job;
    Wife wife;
    public Husband(String name,String job,Wife wife){
        this.name = name;
        this.job = job;
        this.wife = wife;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Husband husband = (Husband) super.clone();
        husband.wife = (Wife)wife.clone();
        return husband;
    }

    @Override
    public String toString() {
        return "Husband{" +
                "name='" + name + '\'' +
                ", job='" + job + '\'' +
                ", wife=" + wife +
                '}';
    }
}

/**
 * 深拷贝的引用类型会新建空间再拷贝一份。所以目标与源都互不干扰。
 */
public class 深拷贝 {
    public static void main(String[] args) throws Exception{
        Wife wife = new Wife("陈圆圆",16);
        Husband husband = new Husband("张帅","将军",wife);
        Husband husband2 = (Husband) husband.clone();
        husband2.wife.name="小泽码丽";
        System.out.println("h2"+husband2.toString());
        System.out.println("h1"+husband.toString());
    }
}

